<template>
  <PageContainer>
    <Header title="选择标签">
      <template>
        <view class="hb-h-9 hb-box-content hb-py-2 hb-px-4">
          <TSearch text="搜索" @confirm="handleConfirm"></TSearch>
        </view>
        <view class="hb-h-10 hb-bg-[#FFF4E7] hb-flex hb-items-center hb-px-4">
          <TmIcon name="ali-icon icon-tips" color="#E29942" :font-size="32" />
          <TmText
            _class="hb-ml-2"
            label="左滑可编辑/删除标签"
            :line-height="44"
            color="#E29942"
            :font-size="28"
          />
        </view>
      </template>
    </Header>
    <view>
      <view class="hb-p-4">
        <TmSlideSwitchGroup :active-open-id="activeOpenId">
          <TmCheckboxGroup v-model="selected">
            <template v-for="v in labelListData" :key="v.id">
              <TmSlideSwitch
                class="hb-mb-3 hb-rounded-lg hb-box-shadow-base"
                :width="686"
                :height="136"
                transparent
                :id="v.id"
                @open="() => (activeOpenId = v.id)"
              >
                <template #right>
                  <view
                    class="hb-h-full hb-flex hb-items-center hb-justify-end hb-rounded-lg hb-overflow-hidden"
                  >
                    <view
                      class="hb-flex-1 hb-h-full hb-bg-[#EA5E0E] hb-flex hb-items-center hb-justify-end"
                    >
                      <view
                        class="hb-w-13 hb-h-full hb-flex hb-items-center hb-justify-center"
                        @click="handleShowDeleteModal(v)"
                      >
                        <TmText label="删除" color="#fff" :font-size="28" />
                      </view>
                    </view>
                    <view
                      class="hb-w-13 hb-h-full hb-bg-primary hb-flex hb-items-center hb-justify-center"
                      @click="handleShowEditModal(v)"
                    >
                      <TmText label="编辑" color="#fff" :font-size="28" />
                    </view>
                  </view>
                </template>
                <view class="hb-p-3 hb-h-full hb-flex hb-items-center hb-bg-white hb-rounded-lg">
                  <TmCheckbox :margin="[0, 0, 24, 0]" :size="40" :value="v.id" />
                  <view
                    class="hb-flex-1 hb-flex hb-flex-col hb-justify-between"
                    @click="handleSelectItem(v)"
                  >
                    <TmText
                      _class="hb-font-bold text-overflow-1"
                      :label="getLabelName(v.label, v.labelUserCount)"
                      :font-size="32"
                    />
                    <TmText
                      v-if="v.botNameList?.length > 0"
                      :label="v.botNameList.join('，')"
                      _class="text-overflow-1 hb-mt-1"
                      color="#969799"
                      :font-size="24"
                    />
                  </view>
                  <view
                    class="hb-pl-3 hb-h-full hb-flex hb-items-center"
                    @click="handleViewTagMember(v)"
                  >
                    <TmIcon name="ali-icon icon-yanjing" color="#969799" :font-size="32" />
                  </view>
                </view>
              </TmSlideSwitch>
            </template>
          </TmCheckboxGroup>
        </TmSlideSwitchGroup>

        <Empty v-if="labelListData.length === 0" />
        <view
          class="hb-h-18 hb-flex hb-items-center hb-justify-center hb-bg-white hb-rounded-[8rpx] hb-border hb-border-dashed hb-border-[#EBEDF0]"
          @click="handleShowCreateModal"
        >
          <TmIcon name="tmicon-plus" :font-size="32" />
          <TmText _class="hb-ml-2" label="新建标签" :font-size="28" />
        </view>
      </view>
      <BottomSubmit :submit-btn-label="submitBtnLabel" @submit="handleSelectSubmit" />

      <TmModal
        v-model:show="showCreateModal"
        ok-text="保存"
        :overlay-click="false"
        :ok-close="false"
        :height="420"
        splitBtn
        :title="editItem ? '编辑标签' : '新建标签'"
        @ok="handleCreateLabel"
        @cancel="handleCancelCreateModal"
      >
        <template>
          <TmForm
            ref="formRef"
            v-model="formData"
            layout="vertical"
            :padding="[0, 0]"
            :margin="[0, 0, 0, 0]"
            :transparent="true"
            :border="false"
          >
            <TmFormItem
              label="标签名称"
              :show-top-error-gap="false"
              required
              :margin="[0, 0]"
              :padding="[0, 0]"
              :transparent="true"
              field="label"
              :rules="rules"
            >
              <TmInput
                v-model="formData.label"
                :font-size="28"
                :height="88"
                show-char-number
                :maxlength="20"
                placeholder="请输入"
              />
            </TmFormItem>
          </TmForm>
        </template>
      </TmModal>

      <TmModal
        v-model:show="deleteModalVisible"
        title="删除标签"
        :height="300"
        :follow-theme="false"
        cancel-text="取消"
        cancel-color="#969799"
        ok-color="#EA5E0E"
        ok-text="确认删除"
        :ok-close="false"
        @ok="handleDeleteLabel"
      >
        <view class="hb-text-sm hb-text-[#333] hb-text-center">
          <text>确定要删除“</text>
          <text class="hb-text-primary">{{ deleteItem?.label }}</text>
          <text>”吗？删除后对应好友的标签将会被删除。</text>
        </view>
      </TmModal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* selectTags 选择标签 */
  import { addOrUpdateLabel, deleteLabel, labelList } from '@/api/contact';
  import { LabelListResult } from '@/api/contact/types';
  import { SelectTags } from '@/router/types/modules';
  import TmForm from '@/tmui/components/tm-form/tm-form.vue';
  import { Toast } from '@/utils';
  import { isArray } from 'lodash-es';

  let success: SelectTags['success'];
  const selected = ref<number[]>([]);
  const showCreateModal = ref(false);
  /** 当前打开的滑块 */
  const activeOpenId = ref<number>();

  const allData = ref<LabelListResult[]>([]);
  const labelListData = ref<LabelListResult[]>([]);
  const getLabelList = (keyWord?: string) => {
    labelList({ keyWord }).then((res) => {
      if (!keyWord) allData.value = res;
      labelListData.value = res;
    });
  };
  getLabelList();

  customOnload<'selectTags'>((op) => {
    if (isArray(op.selected) && op.selected.length > 0) {
      selected.value = op.selected;
    }
    success = op.success;
  });

  const handleSelectItem = (v: LabelListResult) => {
    activeOpenId.value = -1;
    if (selected.value.includes(v.id)) {
      selected.value = selected.value.filter((item) => item !== v.id);
    } else {
      selected.value.push(v.id);
    }
  };

  const rules = ref([{ required: true, message: '请输入标签名称' }]);
  const formRef = ref<InstanceType<typeof TmForm>>();
  const formData = reactive({
    label: '',
  });

  const editItem = ref<LabelListResult>();
  const handleShowEditModal = (v: LabelListResult) => {
    activeOpenId.value = -1;
    formRef.value?.clearValidate();
    showCreateModal.value = true;
    editItem.value = v;
    formData.label = v.label;
  };

  function handleShowCreateModal() {
    activeOpenId.value = -1;
    formRef.value?.clearValidate();
    showCreateModal.value = true;
  }

  function handleCreateLabel() {
    formRef.value?.submit();
    const res = formRef.value?.validate();
    if (res?.isPass) {
      addOrUpdateLabel({ id: editItem.value?.id, label: formData.label }).then((res) => {
        Toast(editItem.value ? '编辑成功' : '创建成功');
        if (editItem.value) {
          labelListData.value = labelListData.value.map((item) => {
            if (item.id === editItem.value!.id) {
              allData.value.find((item) => item.id === editItem.value!.id)!.label = formData.label;
              return { ...item, label: formData.label };
            }
            return item;
          });
          handleSelectSubmit(false);
        } else {
          getLabelList();
        }
        showCreateModal.value = false;
        formData.label = '';
      });
    }
  }

  const handleCancelCreateModal = () => {
    formData.label = '';
    editItem.value = void 0;
  };

  const deleteModalVisible = ref(false);
  const deleteItem = ref<LabelListResult>();
  const handleShowDeleteModal = (v: LabelListResult) => {
    activeOpenId.value = -1;
    deleteItem.value = v;
    deleteModalVisible.value = true;
  };

  const handleDeleteLabel = () => {
    deleteLabel(deleteItem.value!.id).then(() => {
      Toast('删除成功');
      labelListData.value = labelListData.value.filter((item) => item.id !== deleteItem.value!.id);
      allData.value = allData.value.filter((item) => item.id !== deleteItem.value!.id);
      if (selected.value.includes(deleteItem.value!.id)) {
        selected.value = selected.value.filter((item) => item !== deleteItem.value!.id);
        handleSelectSubmit(false);
      }
      deleteItem.value = void 0;
      deleteModalVisible.value = false;
    });
  };

  const getLabelName = (label: string, userCount?: number) => {
    return userCount ? `${label}(${userCount})` : label;
  };

  /** 搜索 */
  const handleConfirm = (val: string) => {
    getLabelList(val);
  };

  const submitBtnLabel = computed(() => `确认选择（${selected.value.length}）`);

  const handleViewTagMember = (v: LabelListResult) => {
    navigateTo({
      name: 'tagMembers',
      options: {
        id: v.id,
        tagName: v.label,
      },
    });
  };

  const handleSelectSubmit = (isBack: boolean = true) => {
    success?.(allData.value.filter((item) => selected.value.includes(item.id)));
    if (isBack) {
      navigateBack();
    }
  };
</script>

<style lang="scss" scoped></style>
